package cn.goktech.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

//为类加上@ControllerAdvice代表当前类是异常处理类，可以捕获全局的异常处理
//注意当前类需要被springmvc自动扫描到
@ControllerAdvice
public class GlobalExceptionHandler {
    private static Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    //通过@ExceptionHandler所注解的方法，分别实现多个不同异常类型所返回的不同异常界面
    @ExceptionHandler(NullPointerException.class)
    public String getUnllExcpt(HttpServletRequest request,
                               HttpServletResponse response,NullPointerException e) {
        log.error("================ start 异常记录==================================");
        String url_error = "http://" + request.getServerName() // 服务器地址
                + ":" + request.getServerPort() // 端口号
                + request.getContextPath() // 项目名称
                + request.getServletPath() // 请求页面或其他地址
                + "?" + (request.getQueryString()); // 参数
        log.error("错误的来源完整异常地址：" + url_error);
        Map<String, String[]> pars = request.getParameterMap();
        Set<String> parameterKey2 = pars.keySet();
        Iterator<String> iterator2 = parameterKey2.iterator();
        while (iterator2.hasNext()) {
            String tKey = iterator2.next();
            String tValue = pars.get(tKey)[0];
            log.error("request提交参数key:" + tKey + " , value值：" + tValue);
        }

        log.error(e.getMessage(), e);// 可以把所有的异常堆栈信息打印出来
        log.error("================ end 异常记录==================================");
        return "error";
    }
    @ExceptionHandler(ArithmeticException.class)
    public String getArithmeterException() {
        return "sm";
    }
}
